package yl.hs.bmipfull.service.production.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import yl.hs.bmipfull.daos.laboratory.IProductInfoDao;
import yl.hs.bmipfull.daos.production.IProductDefectiveDao;
import yl.hs.bmipfull.pojo.laboratory.ProductInfoEntity;
import yl.hs.bmipfull.pojo.production.ProductDefectiveEntity;
import yl.hs.bmipfull.service.production.IProductDefectiveService;
import yl.hs.bmipfull.utils.DataState;
import yl.hs.bmipfull.utils.Tl;
import yl.hs.bmipfull.utils.datastate.ActionType;
import yl.hs.bmipfull.viewmodels.PageQuery;
import yl.hs.bmipfull.viewmodels.PageResult;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作用:  不良品出入库记录服务层接口实现<br/>
 * 创建时间: 2023年08月12日 09时31分37秒 <br/>
 *
 * @author 吴高丰
 */
@Service
public class ProductDefectiveServiceImpl extends ProductionBaseService implements IProductDefectiveService {

    @Autowired
    IProductDefectiveDao dao;
    @Autowired
    IProductInfoDao infoDao;

    @Override
    public List<ProductDefectiveEntity> queryList(PageQuery pageQuery) throws Exception {
        pageQuery.checkSortSides(ProductDefectiveEntity.class);
        return dao.queryPage(pageQuery.getQuery());
    }

    @Override
    public PageResult<ProductDefectiveEntity> queryPage(PageQuery pageQuery, int rowNum, int page) throws Exception {
        pageQuery.checkSortSides(ProductDefectiveEntity.class);
        var resultlist =  queryList(pageQuery);
        pageQuery.getQuery().put("querySkip", (page - 1) * rowNum);
        pageQuery.getQuery().put("pageSize", rowNum);
        pageQuery.getQuery().put("sortKey", String.join(",", pageQuery.getSortSides()));
        PageResult<ProductDefectiveEntity> result = new PageResult(rowNum);
        result.setRecords(dao.queryCountByCondition(pageQuery.getQuery()));
        result.setPage(page);
        result.setData(dao.queryPage(pageQuery.getQuery()));
        Map<String,Object> object = new HashMap<>();
        object.put("weight",resultlist.stream().map(ProductDefectiveEntity::getWeight).reduce(BigDecimal::add));
        object.put("quantity",resultlist.stream().map(ProductDefectiveEntity::getQuantity).reduce(BigDecimal::add));
        result.setObject(object);
        return result;
    }


    @Override
    public ProductDefectiveEntity findBySn(String sn) {
        return dao.findBySN(sn);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveproduct_defective(Map<String, Object> model, String sn) throws Exception {
        Integer result = 0;
        ProductDefectiveEntity entity = null;
        if (Tl.isEmpty(sn)) {
            //执行保存
            entity = new ProductDefectiveEntity();
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            entity.setSn(queryNewSN(ProductDefectiveEntity.class));
            if(entity.getType()==1){
                var product = infoDao.findBySN(entity.getProductSN());
                if(product.getDefectiveWeight().compareTo(entity.getWeight().setScale(2,RoundingMode.HALF_UP))<0){
                    return  -1;
                }
            }
            result = dao.insertNew(entity);
            if (result > 0) {
                updateKc(entity);
                writeLog(ActionType.CREATE, entity.getSn(), "插入不良品出入库记录信息", Tl.toJson(entity), ProductDefectiveEntity.class);
            }

        } else {
            //执行修改
            entity = findBySn(sn);
            Tl.getChangeLog(entity, model);
            entity.setPYFieldValue();
            result = dao.update(entity);
            if (result > 0) {
                writeLog(ActionType.UPDATE, sn, "更新不良品出入库记录信息", Tl.toJson(entity), ProductDefectiveEntity.class);
            }
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer delete(String sn) {
        var sns = sn.split(",");
        Integer result = dao.changeStateBySN(sns, DataState.DELETED.code);
        if (result > 0) {
            var products = dao.findBySN(sn);
            var product = infoDao.findBySN(products.getProductSN());
            if (product != null) {
                var weight = product.getDefectiveWeight();
                var quantity = product.getDefectiveQuantity();
                if (products.getType() == 2) {
                    infoDao.updateDefective(products.getProductSN(),weight.subtract(products.getWeight()),quantity.subtract(products.getQuantity()));
                    writeLog(ActionType.DELETE, product.getSn(), "删除不良品出入库记录信息,库存由"+weight.setScale(2, RoundingMode.DOWN)+"变为"+weight.subtract(products.getWeight()).setScale(2,RoundingMode.DOWN), Tl.toJson(product), ProductInfoEntity.class);
                } else {
                    infoDao.updateDefective(products.getProductSN(),weight.add(products.getWeight()),quantity.add(products.getQuantity()));
                    writeLog(ActionType.DELETE, product.getSn(), "删除不良品出出库记录信息,库存由"+weight.setScale(2, RoundingMode.DOWN)+"变为"+weight.add(products.getWeight()).setScale(2,RoundingMode.DOWN), Tl.toJson(product), ProductInfoEntity.class);
                }
            }
            writeLog(ActionType.DELETE, sns, ProductDefectiveEntity.class);
        }
        return result;
    }

    public void updateKc(ProductDefectiveEntity entity) {
        var product = infoDao.findBySN(entity.getProductSN());
        if (product != null) {
            var weight = product.getDefectiveWeight();
            var quantity = product.getDefectiveQuantity();
            if (entity.getType() == 2) {
                infoDao.updateDefective(entity.getProductSN(),weight.add(entity.getWeight()),quantity.add(entity.getQuantity()));
                writeLog(ActionType.UPDATE, product.getSn(), "插入不良品出入库记录信息,库存由"+weight.setScale(2, RoundingMode.DOWN)+"变为"+weight.add(entity.getWeight()).setScale(2,RoundingMode.DOWN), Tl.toJson(product), ProductInfoEntity.class);
            } else {
                infoDao.updateDefective(entity.getProductSN(),weight.subtract(entity.getWeight()),quantity.subtract(entity.getQuantity()));
                writeLog(ActionType.UPDATE, product.getSn(), "插入不良品出出库记录信息,库存由"+weight.setScale(2, RoundingMode.DOWN)+"变为"+weight.subtract(entity.getWeight()).setScale(2,RoundingMode.DOWN), Tl.toJson(product), ProductInfoEntity.class);
            }
        }
    }
}